package com.sshtools.cmd.action;

import com.jcraft.jsch.Session;
import com.sshtools.utils.SSHUtils;
import com.sshtools.view.model.ServerModel;

import tsif.component.log.Log;
import tsif.utils.StringUtils;

/**
 * SSH服务器指令任务
 * 
 * 
 **/
public abstract class ServerCmdTask extends ServerTask {

	public ServerCmdTask(ServerModel server) {
		super(server);
	}

	@Override
	protected void execute(Session session) {
		// 遍历指令
		String[] commands = getCommand();
		if (commands == null) {
			throw new NullPointerException("commands is null");
		}
		// 获取远程目录(没有则用上传目录)
		String remotePath = server.getRemotePath();
		remotePath = (!StringUtils.isEmpty(remotePath)) ? remotePath : server.getUploadPath();

		// 遍历指令
		for (String command : commands) {
			if (command == null || command.length() <= 0) {
				Log.error("exec " + server + " :" + command + " is empty.");
				continue; // 空指令, 跳过
			}
			try {
				Log.info(execCmdHead(command) + " star.");
				String retStr = SSHUtils.execCmd(session, command, remotePath);
				Log.info(execCmdHead(command) + retStr);
				Log.info(execCmdHead(command) + " finish.");
			} catch (Exception e) {
				Log.error(execCmdHead(command) + " error.", e);
			}
		}
	}

	/** 字符串头 **/
	protected String execCmdHead(String command) {
		return "exec " + server + " " + command;
	}

	/** 指令列表 **/
	protected abstract String[] getCommand();

}
